<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单ID" prop="id">
              <el-input v-model="queryParams.id" placeholder="请输入订单ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="茶室名称" prop="tearoomName">
              <el-input v-model="queryParams.tearoomName" placeholder="请输入茶室名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="入住开始" prop="startTime">
              <el-date-picker 
              clearable
                v-model="queryParams.startTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择入住开始日期时间"
              />
            </el-form-item>
            <el-form-item label="入住结束" prop="endTime">
              <el-date-picker 
              clearable
                v-model="queryParams.endTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择入住结束日期时间"
              />
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="queryParams.mobile" placeholder="请输入入住人电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="queryParams.paymentMethod" placeholder="请选择支付方式" clearable>
                <el-option v-for="dict in order_payment_method" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态" prop="orderStatusList">
              <el-select v-model="queryParams.orderStatusList" multiple placeholder="请选择订单状态" clearable>
                <el-option v-for="dict in ter_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['tearoom:order:edit']">更换舱体</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleFixOrder()" v-hasPermi="['tearoom:order:edit']">更新异常订单</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain :disabled="multiple" @click="handleDelete()" v-hasPermi="['tearoom:order:remove']">订单退回</el-button>
          </el-col>  -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['tearoom:order:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单ID" align="center" prop="id" v-if="true" width="240px" />
        <el-table-column label="用户ID" align="center" prop="userId" v-if="false" />
        <el-table-column label="茶室名称" align="center" prop="tearoomName" width="100px" />
        <el-table-column label="茶室ID" align="center" prop="tearoomId" v-if="false" />
        <el-table-column label="预约时间" align="center" prop="startTime" width="190px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.viewStartTime, '{m}-{d} {h}:{i}') }}~{{ parseTime(scope.row.viewEndTime, isSameDay(scope.row.viewStartTime, scope.row.viewEndTime) ? '{h}:{i}' : '{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入住时间" align="center" prop="startTime" width="190px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{m}-{d} {h}:{i}') }}~{{ parseTime(scope.row.endTime, isSameDay(scope.row.startTime, scope.row.endTime) ? '{h}:{i}' : '{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预定时间" align="center" prop="presetTime">
          <template #default="scope">
            <div>{{ scope.row.presetTime }}小时</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170px" />
        <el-table-column label="订单状态" align="center" prop="orderStatus">
          <template #default="scope">
            <dict-tag :options="ter_order_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="订单总价" align="center" prop="totalPrice">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.totalPrice) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="优惠" align="center" prop="discount">
          <template #default="scope">
            <div>{{ discountFormat(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center" prop="paymentMethod" />
        <el-table-column label="支付金额" align="center" prop="prepayAmount" >
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.prepayAmount) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="预计收入" align="center" prop="prepayAmount" >
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.revenue) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="入住人电话" align="center" prop="mobile" width="120px"/>
        <el-table-column label="续单订单ID" align="center" prop="oldId" width="240px" />
        <el-table-column label="门锁密钥" align="center" prop="doorKey" />
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="退款" placement="top">
              <el-button
                link
                type="primary"
                icon="CreditCard"
                :disabled="scope.row.orderStatus === '6' || scope.row.orderStatus === '5'"
                @click="handleDelete(scope.row)"
                v-hasPermi="['tearoom:order:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="茶室选择" prop="regionalIds">
          <el-select v-model="form.tearoomId" filterable clearable placeholder="请选择茶室" :loading="loading">
            <el-option v-for="item in options" :key="item.id" :label="item.teroomName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择入住开始日期时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择入住结束日期时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
import { listOrder, addOrder, updateOrder, orderRefund, replaceOrder } from '@/api/tearoom/order';
import { RoomDetailsVO } from '@/api/tearoom/roomDetails/types';
import { OrderVO, OrderQuery, OrderForm } from '@/api/tearoom/order/types';
import { floatToFixed2 } from '@/utils/index';
import { getRoomList } from '@/api/tearoom/roomDetails';
import dayjs from 'dayjs';
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ter_order_status,order_payment_method } = toRefs<any>(
  proxy?.useDict('ter_order_status','order_payment_method')
);
const orderList = ref<OrderVO[]>([]);
const options = ref<RoomDetailsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderForm = {
  id: undefined,
  userId: undefined,
  tearoomName: undefined,
  tearoomId: undefined,
  startTime: undefined,
  endTime: undefined,
  presetTime: undefined,
  orderStatus: undefined,
  totalPrice: undefined,
  prepayAmount: undefined,
  mobile: undefined,
  couponId: undefined,
  paymentMethod: undefined,
  doorKey: undefined,
}
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    userId: undefined,
    tearoomName: undefined,
    tearoomId: undefined,
    startTime: undefined,
    endTime: undefined,
    presetTime: undefined,
    orderStatus: undefined,
    totalPrice: undefined,
    prepayAmount: undefined,
    mobile: undefined,
    couponId: undefined,
    paymentMethod: undefined,
    doorKey: undefined,
    orderStatusList: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "订单id不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户id不能为空", trigger: "blur" }
    ],
    tearoomName: [
      { required: true, message: "茶室名称不能为空", trigger: "blur" }
    ],
    tearoomId: [
      { required: true, message: "茶室id不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "入住开始日期时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "入住结束日期时间不能为空", trigger: "blur" }
    ],
    presetTime: [
      { required: true, message: "预定时间(h)不能为空", trigger: "blur" }
    ],
    orderStatus: [
      { required: true, message: "订单状态不能为空", trigger: "change" }
    ],
    totalPrice: [
      { required: true, message: "订单总价不能为空", trigger: "blur" }
    ],
    mobile: [
      { required: true, message: "入住人电话不能为空", trigger: "blur" }
    ],
  }
});
// 初始化查询参数（带时间处理）
// 加强校验逻辑（参考）
const initQueryParams = () => {
  const { startTime, endTime } = route.query; // 已自动解码的查询参数

  // 直接验证日期格式
  const validateDate = (time: string) => {
    if (!dayjs(time, 'YYYY-MM-DD HH:mm:ss', true).isValid()) {
      throw new Error('Invalid Date');
    }
    return time;
  };

  try {
    queryParams.value.startTime = startTime ? validateDate(startTime as string) : dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss');
    queryParams.value.endTime = endTime ? validateDate(endTime as string): dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');
  } catch (e) {
    ElMessage.error('日期参数格式错误');
    // 设置安全默认值
    queryParams.value.startTime = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss');
    queryParams.value.endTime = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');
  }
}

const { queryParams, form, rules } = toRefs(data);

/** 查询订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrder(queryParams.value);
  orderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}
const fetchData = async () => {
  loading.value = true;
  const response = await getRoomList();
  console.log('下拉选项数据:', response.data);
  options.value = response.data;
  loading.value = false;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}
/** 更新异常订单操作 */
const handleFixOrder = async () => {
  try {
    // 检查是否选中单条
    if (single.value) {
      proxy?.$modal.msgError('请选择一条数据');
      return;
    }
    const id = ids.value[0];
    // 获取订单详情
    const orderDetail = orderList.value.find(item => item.id === id);
    console.log(orderDetail);
    // 校验状态是否为1（已确认）
    if (orderDetail.orderStatus !== '1') {
      proxy?.$modal.msgError('请选择状态为已确认的订单');
      return;
    }
    // 用户确认操作
    await proxy?.$modal.confirm('确认要更新该异常订单吗？');
    buttonLoading.value = true;
    // 提交更新
    await updateOrder(orderDetail);
    proxy?.$modal.msgSuccess('更新成功');
    await getList();
  } catch (error) {
    // 处理用户取消或请求错误
    if (error !== 'cancel') {
      proxy?.$modal.msgError('更新失败，请重试');
    }
  } finally {
    buttonLoading.value = false;
  }
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  orderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加订单";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const orderDetail = orderList.value.find(item => item.id === _id);
  form.value = {
    ...orderDetail,
    tearoomId: orderDetail.tearoomId,
    startTime: orderDetail.startTime,
    endTime: orderDetail.endTime
  };
  dialog.visible = true;
  dialog.title = "更换舱体";
}

/** 提交按钮 */
const submitForm = () => {
  const selectedItem = options.value.find((item) => item.id === form.value.tearoomId);
  if (selectedItem) {
    form.value.tearoomName = selectedItem.teroomName;
  }
  orderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await replaceOrder(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addOrder(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: OrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认退回订单编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  Object.assign(form.value, row);
  await orderRefund(form.value);
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('tearoom/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}
// 格式化【优惠金额/折扣】
const discountFormat = (row: OrderVO) => {
  if (row.couponHour) {
    return +row.couponHour+`小时`;
  }
  if (row.couponPrice) {
    return `￥${floatToFixed2(row.couponPrice)}`;
  }
};
// 是否是同一天
const isSameDay=(a, b)=>{
  return dayjs(a).isSame(dayjs(b), 'day')
}

watch(() => route.query,
  (newQuery) => {
    initQueryParams();
    fetchData();
    getList();
  }
);
onMounted(() => {
  initQueryParams();
  fetchData();
  getList();
});
</script>